﻿using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Threading;
using AutoMapper;
using MyCompanyName.AbpZeroTemplate.Card.Dto;
using MyCompanyName.AbpZeroTemplate.IRepositorys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompanyName.AbpZeroTemplate.Card
{
    public class CardService : AbpZeroTemplateAppServiceBase, ICardService
    {
        private readonly ICardRepository _cardRepository;
        private readonly ITransferCardLogRepository _transferCardLogRepository;
        private readonly ICardRechargeLogRepository _cardRechargeLogRepository;
        public CardService(ICardRepository cardRepository,
                            ITransferCardLogRepository transferCardLogRepository,
                            ICardRechargeLogRepository cardRechargeLogRepository)
        {
            this._cardRepository = cardRepository;
            this._transferCardLogRepository = transferCardLogRepository;
            this._cardRechargeLogRepository = cardRechargeLogRepository;
        }

        #region 卡片
        /// <summary>
        /// 获得卡片列表
        /// </summary>
        /// <returns></returns>
        public PagedResultDto<CardDto> GetCardDtoList(string CardName, int PageSize, int PageNumber)
        {
            var obj = _cardRepository.GetAll();

            //判断逻辑

            //获取总数
            var dataCount = obj.Count();

            //默认的分页方式
            var dataList = obj.Where(m => m.UCCID.Contains(CardName))
                              .OrderByDescending(t => t.CreationTime)
                              .Skip(PageSize * (PageNumber - 1)).Take(PageSize).ToList();
            return new PagedResultDto<CardDto>(dataCount, dataList.MapTo<List<CardDto>>());
        }

        /// <summary>
        /// 根据卡片主键id获得代理商信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public CardDto GetCardById(int Id)
        {
            CardDto result = new CardDto();

            var obj = _cardRepository.Get(Id);
            result = obj.MapTo<CardDto>();
            return result;
        }
        /// <summary>
        /// 根据卡号获取信息
        /// </summary>
        /// <param name="Account"></param>
        /// <returns></returns>
        public CardDto GetAgentByCard(string Card)
        {
            var obj = _cardRepository.GetAll().Where(p => p.UCCID.Equals(Card)).FirstOrDefault();
            return obj.MapTo<CardDto>();
        }
        /// <summary>
        /// 创建卡片
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public int CreateCard(CreateCardInput input)
        {
            int result = 0;

            var task = Mapper.Map<Card>(input);
            task.CreationTime = DateTime.Now;
            task.Invalid_time = Convert.ToDateTime("1971-01-01 00:00:00");
            task.BindTime = Convert.ToDateTime("1971-01-01 00:00:00");

            result = _cardRepository.InsertAndGetId(task);


            return result;
        }
        /// <summary>
        /// 更新卡片
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool UpdateCard(UpdateCardInput input)
        {
            bool result = false;
            try
            {
                //获取当前用户
                var currentUser = AsyncHelper.RunSync(this.GetCurrentUserAsync);
                var obj = _cardRepository.Get(input.Id);
                obj.UCCID = input.UCCID;
                obj.Remark = input.Remark;
                obj.Status = input.Status;
                obj.AgentCode = input.AgentCode;
                obj.Package = input.Package;
                obj.Balance = input.Balance;
                obj.Proportion = input.Proportion;
                obj.Invalid_time = input.Invalid_time;
                obj.BindTel = input.BindTel;
                obj.BindTime = input.BindTime;
                obj.BindName = input.BindName;
                obj.BindIdCard = input.BindIdCard;
                //var updateObj = Mapper.Map<FLowSet>(input);
                //_flowSetRepository.Update(updateObj);
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        #endregion

        #region 划卡记录
        /// <summary>
        /// 获得划卡记录列表
        /// </summary>
        /// <returns></returns>
        public PagedResultDto<TransferCardLogDto> GetTransferCardLogDtoList(string TransferCardLogName, int PageSize, int PageNumber)
        {
            var obj = _transferCardLogRepository.GetAll();

            //判断逻辑

            //获取总数
            var dataCount = obj.Count();

            //默认的分页方式
            var dataList = obj.Where(m => m.UCCID.Contains(TransferCardLogName))
                              .OrderByDescending(t => t.CreationTime)
                              .Skip(PageSize * (PageNumber - 1)).Take(PageSize).ToList();
            return new PagedResultDto<TransferCardLogDto>(dataCount, dataList.MapTo<List<TransferCardLogDto>>());
        }
        /// <summary>
        /// 创建划卡记录,更新卡片信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string CreateTransferCard(CreateTransferCardLogInput input)
        {
            bool flag = true;
            string resultStr = "";
            string ErrorMsg = "";
            try
            {
                //获取当前用户
                var currentUser = AsyncHelper.RunSync(this.GetCurrentUserAsync);
                var obj = Mapper.Map<TransferCardLog.TransferCardLog>(input);
                obj.OwnerId = currentUser.Id.ToString();
                obj.CreationTime = DateTime.Now;
                obj.R_Id = Guid.NewGuid();

                //获得当前代理商号段的卡号

                List<Card> listCard = _cardRepository.UpdateAgentCodeForCard(currentUser.UserName, input.UccidStart, input.UccidEnd);

                foreach (var item in listCard)
                {
                    item.AgentCode = input.AgentCode;
                }

                //创建划卡记录
                int _result = _transferCardLogRepository.InsertAndGetId(obj);
            }
            catch (Exception ex)
            {
                flag = false;
                ErrorMsg = ex.Message;
            }
            return "{\"status\":\"" + flag + "\",\"errormsg\":\"" + ErrorMsg + "\"}";
        }
        #endregion

        #region 充值记录
        /// <summary>
        /// 获得充值记录列表
        /// </summary>
        /// <returns></returns>
        public PagedResultDto<CardRechargeLogDto> GetCardRechargeLogDtoList(string CardRechargeLogName, int PageSize, int PageNumber)
        {
            var obj = _cardRechargeLogRepository.GetAll();

            //判断逻辑

            //获取总数
            var dataCount = obj.Count();

            //默认的分页方式
            var dataList = obj.Where(m => m.UCCID.Contains(CardRechargeLogName))
                              .OrderByDescending(t => t.CreationTime)
                              .Skip(PageSize * (PageNumber - 1)).Take(PageSize).ToList();
            return new PagedResultDto<CardRechargeLogDto>(dataCount, dataList.MapTo<List<CardRechargeLogDto>>());
        }

        /// <summary>
        /// 创建充值记录,更新卡片信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string CreateCardRecharge(CreateCardRechargeLogInput input)
        {
            bool flag = true;
            string resultStr = "";
            string ErrorMsg = "";
            try
            {
                //获取当前用户
                var currentUser = AsyncHelper.RunSync(this.GetCurrentUserAsync);
                var obj = Mapper.Map<CardRechargeLog.CardRechargeLog>(input);
                obj.OwnerId = currentUser.Id.ToString();
                obj.CreationTime = DateTime.Now;
                obj.R_Id = Guid.NewGuid();


                //充值
                //调用接口
                Card card = _cardRepository.GetAll().Where(p => p.UCCID.Equals(input.UCCID)).FirstOrDefault();
                card.Balance += input.Qty;

                //充值记录
                int _result = _cardRechargeLogRepository.InsertAndGetId(obj);
            }
            catch (Exception ex)
            {
                flag = false;
                ErrorMsg = ex.Message;
            }
            return "{\"status\":\"" + flag + "\",\"errormsg\":\"" + ErrorMsg + "\"}";
        }
        #endregion
    }
}
